package com.lingyuan.warehouse.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingyuan.common.core.domain.vo.call.WmsConstant;
import com.lingyuan.warehouse.domain.WmsPurchase;
import com.lingyuan.warehouse.domain.WmsWareSkuPO;
import com.lingyuan.warehouse.mapper.WareMapper;
import com.lingyuan.common.core.domain.vo.wms.WmsWareSkuVO;
import io.swagger.v3.core.util.Json;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author：寇可往，我亦可往。
 * @Package：com.lingyuan.warehouse.config
 * @Project：lingyuan-shopping-mall
 * @name：RedisConssion
 * @Date：2024/9/18 12:19
 */
@Component
@Log4j2
public class RedisConssion implements ApplicationRunner {

    @Autowired
    private WareMapper wareMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void run(ApplicationArguments args){
        //开局自启
        //库存存入redis===>预热
        List<WmsWareSkuVO> LhList = wareMapper.list();
        LhList.forEach ( item -> {
            redisTemplate
                    .boundHashOps(WmsConstant.WARE_LOCK_KEY_VALUE)
                    .put (String.valueOf(item.getSkuId()),String.valueOf(item.getStock() - item.getStockLocked()));
        });
//       initWareSku();
    }

    /**
     * TODO 用户；列表预警
     */

//    @Scheduled(cron = "0 0/1 * * * ?") //每10分钟
    public void initWareSku(){
        redisTemplate.delete ( WmsConstant.WARE_LOCK_KEY );
        //存入redis过期时间10分钟
        redisTemplate.expire ( WmsConstant.WARE_LOCK_KEY, 10, TimeUnit.MINUTES );
        List<WmsWareSkuVO> list = wareMapper.getWareSkuList ();
        redisTemplate.opsForList ().leftPushAll ( Constant.WARE_LOCK_KEY, JSON.toJSONString(list) );
        if (redisTemplate.hasKey ( WmsConstant.WARE_LOCK_KEY )){
            System.out.println ( "redis中wareSkuList数据更新成功" );
        }else {
            System.out.println ( "redis中wareSkuList数据更新失败" );
            initWareSku ();
        }
    }
}
